package com.linkage.educloud.ah.view.fragment;


import android.annotation.SuppressLint;
import android.database.Cursor;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.Nullable;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.linkage.educloud.ah.MyApplication;
import com.linkage.educloud.ah.R;
import com.linkage.educloud.ah.adapter.MessageAdapter;
import com.linkage.educloud.ah.config.AccountConfig;
import com.linkage.educloud.ah.data.Ws;
import com.linkage.educloud.ah.decoration.LinerItemNoPaddingDecoration;
import com.linkage.educloud.ah.listener.OnItemClickListener;
import com.linkage.educloud.ah.mvp.contract.IMessageContract;
import com.linkage.educloud.ah.mvp.presenter.MessagePresenter;
import com.linkage.educloud.ah.view.BasicFragment;
import com.zzhou.common.library.util.DisplayUtils;
import com.zzhou.common.library.util.LogUtils;

import butterknife.BindView;

/**
 * <desc>
 * Created by The Moss on 2018/7/25.
 */

public class MessageFragment extends BasicFragment implements IMessageContract.IView,OnItemClickListener {

    @BindView(R.id.fragment_recyclerView)
    XRecyclerView mRecyclerView;
    @BindView(R.id.fragment_stutas_view)
    View mStutasView;

    boolean traFlag = false;
    private MessageAdapter mAdapter;
    IMessageContract.IPresenter iPresenter;

    public static MessageFragment newInstance() {
        MessageFragment fragment = new MessageFragment();
        return fragment;
    }

    @Override
    protected int attachLayoutRes() {
        return R.layout.fragment_message;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        iPresenter = new MessagePresenter(this);
        initRecyclerView();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    @Override
    public void onLoadDatasFromServer(boolean isSuccess, String msg) {
        if (mAdapter == null) {
            new Handler(Looper.getMainLooper()).post(new Runnable() {
                @Override
                public void run() {
                    Cursor cursor = MyApplication.getInstance().getResovler().queryThreadOrderByType(AccountConfig.getLoginAccount().getLoginAccount());
                    LogUtils.d("cursor size = " + cursor.getCount());
                    mAdapter = new MessageAdapter(getActivity(),cursor,1,MessageFragment.this);
                    mRecyclerView.setAdapter(mAdapter);
                }
            });
        }
    }

    @SuppressLint("NewApi")
    private void initRecyclerView() {
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        mRecyclerView.addItemDecoration(new LinerItemNoPaddingDecoration());
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mRecyclerView.addOnScrollListener(onScrollListener);

        mRecyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                new Thread() {
                    @Override
                    public void run() {
                        try {
//                            Thread.sleep(3000);
//                            mRecyclerView.refreshComplete();
                            iPresenter.loadDatasFromServer();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }.start();
            }

            @Override
            public void onLoadMore() {
                new Thread() {
                    @Override
                    public void run() {
                        try {
                            Thread.sleep(3000);
                            mRecyclerView.loadMoreComplete();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }.start();
            }
        });
        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                LinearLayoutManager lm = (LinearLayoutManager) recyclerView.getLayoutManager();
                int totalItemCount = recyclerView.getAdapter().getItemCount();
                int lastVisibleItemPosition = lm.findLastVisibleItemPosition();
                int visibleItemCount = recyclerView.getChildCount();

                if (newState == RecyclerView.SCROLL_STATE_IDLE
                        && lastVisibleItemPosition == totalItemCount - 3
                        && visibleItemCount > 0) {

                }
            }
        });
        mRecyclerView.refresh();
        initLoader();
    }
    @Override
    public void onItemClick(View v, int position) {
        LogUtils.d("position = " + position);
        if (position == 1) {
            mRecyclerView.refresh();
        }else if (position == mAdapter.getItemCount()) {
//            iPresenter.getMessItemFromServer(MessagePresenterImpl.LOADMORE_VIEW);
        }
    }
    private void setStutaslayoutAlpha(float percentage) {
//        LogUtils.e("percentage = " + percentage);

        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                if (percentage > 1) {
                    percentage = 1;
                    traFlag = true;
                } else {
                    traFlag = false;
                }
                if (traFlag) {//已经显示的，不在往下执行
                    return;
                }
                int background = (int) (255 * percentage);
                mStutasView.getBackground().mutate().setAlpha(background);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    private RecyclerView.OnScrollListener onScrollListener = new RecyclerView.OnScrollListener() {
        int mScroll = 0;
        int maxScroll = DisplayUtils.dip2px(450);

        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
            super.onScrollStateChanged(recyclerView, newState);
        }

        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            mScroll += dy;
            float percent = (float) Math.abs(mScroll) / (float) maxScroll;
            setStutaslayoutAlpha(percent);
        }
    };
    private void initLoader() {
        getLoaderManager().initLoader(1, null, new LoaderManager.LoaderCallbacks<Cursor>() {
            @Override
            public Loader<Cursor> onCreateLoader(int id, Bundle args) {

                CursorLoader loader = new CursorLoader(getActivity(), Ws.ThreadTable.CONTENT_URI, null, Ws.ThreadTable.ACCOUNT_NAME + " = ?"
                        , new String[]{AccountConfig.getLoginAccount().getLoginAccount()}
                        , Ws.ThreadTable.THREAD_TYPE + " asc," + Ws.ThreadTable.MSG_RECEIVED_TIME + " desc");

                return loader;
            }

            @Override
            public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
                try {
                    mAdapter.swapCursor(data);
                    mRecyclerView.refreshComplete();
                    mRecyclerView.loadMoreComplete();
                } catch (Exception e) {
                }
            }

            @Override
            public void onLoaderReset(Loader<Cursor> loader) {
                try {
                    mAdapter.swapCursor(null);
                } catch (Exception e) {
                }
            }
        });
    }
}
